;(function () {

    const list = $('.list');
    const listHeight = list.height();
    const n = Math.ceil(listHeight / 40) + 2;

    function init (name) {
        list.html('');
        for (let i = 0; i < n; i++) {
            const el = $(`
                <div 
                    class="item"
                    style="top: ${ i * 40 }px"
                >
                    <div class="inner">
                        <div>${ moment(monitor[name][i].timestamp).format('YYYY-MM-DD') }</div>
                        <div>${ monitor[name][i].address }</div>
                        <div>${ monitor[name][i].code }</div>
                    </div>
                </div>
            `);
            list.append(el);
        }
    }

    let timer = null;
    let m = 0;

    function animate (name) {
        timer = setInterval(function () {
            $('.list .item').each(function (i, item) {
                const style = $(item).attr('style');
                const top = parseInt(style.split(': ')[1]);
                if (top !== -40) {
                    $(item).attr('style', `top: ${ top - 40 }px; visibility: visible;`);
                } else {
                    $(item).attr('style', `top: ${ (n - 2) * 40 }px; visibility: hidden;`);
                    const currentDataItem = monitor[name][(n + m - 1) % monitor[name].length];

                    $(item).children('.inner').children().eq(0).html(moment(currentDataItem.timestamp).format('YYYY-MM-DD'));
                    $(item).children('.inner').children().eq(1).html(currentDataItem.address);
                    $(item).children('.inner').children().eq(2).html(currentDataItem.code);
                }
            });
            m++;
        }, 1000);
    }

    $('#breakdown').on('click', function () {
        $(this)
            .addClass('active')
            .siblings()
            .removeClass('active');
            
        init('breakdown');
        $('.monitor-wrapper .header .inner div').eq(0).text('故障时间');
        $('.monitor-wrapper .header .inner div').eq(2).text('故障代码');
    });

    $('#error').on('click', function () {
        $(this)
            .addClass('active')
            .siblings()
            .removeClass('active');
        
        init('error');
        $('.monitor-wrapper .header .inner div').eq(0).text('异常时间');
        $('.monitor-wrapper .header .inner div').eq(2).text('异常代码');
    });

    $('.monitor-wrapper').on('mouseover', function () {
        clearInterval(timer);
    });

    $('.monitor-wrapper').on('mouseout', function () {
        const btn = $('.monitor-wrapper').find('.active');
        animate( btn.attr('id') );
    });

    init('breakdown');
    animate('breakdown');

    console.log(moment(1631517023803).format('YYYYMMDD'))

})();